package chapter4.RPC;

import com.rabbitmq.client.*;
import util.Conn;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * Created by uu on 2017/6/21.
 */
public class rpc_client {
        private static final String QUEUE_NAME = "king";
    public static void main(String[] args) throws Exception{
        Connection conn = new Conn().getConnection();
        final Channel channel = conn.createChannel();
        channel.exchangeDeclare("rpc","direct",true);
        channel.queueDeclare(QUEUE_NAME,true,true,true,null);
        channel.queueBind(QUEUE_NAME,"rpc",QUEUE_NAME);
        AMQP.BasicProperties properties = new AMQP.BasicProperties();
        properties = properties.builder().replyTo(QUEUE_NAME).build();
        String body = "lp is linpeng"+ new Date();
        channel.basicPublish("rpc","ping",properties,body.getBytes());
        System.out.println("Sent 'ping' RPC call.Waiting for reply...");
        channel.basicConsume(QUEUE_NAME,false,QUEUE_NAME,new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String routingKey = envelope.getRoutingKey();
                String contentType = properties.getContentType();
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("RPC Reply ---"+new String(body,"UTF-8"));
                channel.basicCancel(QUEUE_NAME);
                // (process the message components here ...)

            }
        });
    }
}
